import AuthAPI, { type LoginData } from "@/api/auth";
import UserAPI, { type UserInfo } from "@/api/user";
import { resetRouter } from "@/router";
import { store } from "@/store";
import { setToken, removeToken } from "@/utils/auth";
import PermApi from "@/api/role";

export const useUserStore = defineStore("user", () => {
  const user = ref({
    roles: [],
    perms: [],
    username: "",
  });

  /**
   * 登录
   *
   * @param {LoginData}
   * @returns
   */
  function login(loginData: LoginData) {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.login(loginData)
        .then((data) => {
          console.log("dadadada", data);

          // console.log(';datdad',data.token);

          const { tokenType, accessToken } = data;
          setToken(data.result.token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          localStorage.setItem("username", data.result.userInfo.name);
          user.value.username = data.result.userInfo.name;
          // localStorage.setItem("userName", data.result.userInfo.name);
          resolve();
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  // 获取信息(用户昵称、头像、角色集合、权限集合)
  function getUserInfo() {
    return new Promise<UserInfo>(async (resolve, reject) => {
      // let arr = {
      //   userId: 2,
      //   username: "贵宾专车",
      //   nickname: "系统管理员",
      //   avatar: "https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif",
      //   roles: ["ADMIN"],
      //   perms: [
      //     "sys:notice:edit",
      //     "sys:menu:delete",
      //     "sys:dict:edit",
      //     "sys:notice:query",
      //     "sys:dict:delete",
      //     "sys:config:add",
      //     "sys:config:refresh",
      //     "sys:menu:add",
      //     "sys:user:add",
      //     "sys:user:export",
      //     "sys:role:edit",
      //     "sys:dept:delete",
      //     "sys:config:update",
      //     "sys:user:password:reset",
      //     "sys:notice:revoke",
      //     "sys:user:import",
      //     "sys:user:delete",
      //     "sys:dict_type:delete",
      //     "sys:dict:add",
      //     "sys:role:add",
      //     "sys:notice:publish",
      //     "sys:notice:delete",
      //     "sys:dept:edit",
      //     "sys:dict_type:edit",
      //     "sys:user:query",
      //     "sys:user:edit",
      //     "sys:config:delete",
      //     "sys:dept:add",
      //     "sys:notice:add",
      //     "sys:role:delete",
      //     "sys:menu:edit",
      //     "sys:config:query",
      //   ],
      // };
      let { code, result } = await PermApi.getBtnPerms();
      if (code == 0) {
        let arr = {
          perms: result,
          roles: ["ADMIN"],
        };
        Object.assign(user.value, { ...arr });
        resolve(arr);
        return;
      }

      // PermApi.getBtnPerms().then((res) => {
      //   if (res.code == 0) {
      //     user.value.perms = res.result;
      //   }
      // });
      // Object.assign(user.value, { ...arr });
      // resolve(arr);
      // return;
    });
  }

  // user logout
  function logout() {
    return new Promise<void>((resolve, reject) => {
      AuthAPI.logout()
        .then(() => {
          removeToken();
          location.reload(); // 清空路由
          resolve();
        })
        .catch((error) => {
          // reject(error);
        });
    });
  }

  // remove token
  function resetToken() {
    return new Promise<void>((resolve) => {
      removeToken();
      resetRouter();
      resolve();
    });
  }

  return {
    user,
    login,
    getUserInfo,
    logout,
    resetToken,
  };
});

/**
 * 用于在组件外部（如在Pinia Store 中）使用 Pinia 提供的 store 实例。
 * 官方文档解释了如何在组件外部使用 Pinia Store：
 * https://pinia.vuejs.org/core-concepts/outside-component-usage.html#using-a-store-outside-of-a-component
 */
export function useUserStoreHook() {
  return useUserStore(store);
}
